package com.wdl.datarest.implementation;

import java.util.Date;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

import io.netty.channel.Channel;

/**
 * 定时器，定时发送命令
 * 
 * @author Administrator
 *
 */
@Component
public class CmdTimer {
	
	@Value("${cmd.heart.freq}")
	private int freq;// 连接地址

	@Autowired
	private TaskScheduler scheduler;

	@PostConstruct
	private void init() {
		long delay = freq * 60 * 1000l;
		startTask(delay);
		System.out.println("定时（"+freq+"分钟）测量心率服务启动成功。。。");

	}

	public void startTask(long delay) {
		Date start = new Date(new Date().getTime() + 300000l);
		scheduler.scheduleWithFixedDelay(new SchedulPortDataAlarmTask(), start, delay);
	}

	private class SchedulPortDataAlarmTask implements Runnable {
		@Override
		public void run() {
			try {
				Map<String, Channel> smap = NettyConfig.sessionChannelMap;

				if (smap == null || smap.isEmpty()) {
					return;
				}

				System.out.println();
				for (String devId : smap.keySet()) {
					//System.out.println("---------------发送定位命令："+devId);
					NettyConfig.sendMessage(devId, "[3g*"+devId+"*0002*CR]");
					
					//System.out.println("---------------发送心率命令："+devId);
					NettyConfig.sendMessage(devId, "[3g*"+devId+"*000A*hrtstart,1]");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
